package com.cmcc.linlaker.volley;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.lang.ref.WeakReference;
import java.util.Map;

/**
 * Created by ZX on 2015/7/14.
 */
public class GsonRequestHelper implements Response.Listener, Response.ErrorListener {

    public interface OnResponseListener {

        public void onError(VolleyError error);

        public void onSuccess(Object data);
    }

    private WeakReference<Context> context;

    private Dialog dialog;

    private OnResponseListener onResponseListener;

    public GsonRequestHelper(Context context) {
        this.context = new WeakReference<Context>(context);
    }

    protected GsonRequest getRequestForGet(String url, Class clazz, boolean isShowDialog) {
        initDialog(isShowDialog);
        GsonRequest request = new GsonRequest(Request.Method.GET, url, clazz, this, this);
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        return request;
    }

    protected GsonRequest getRequestForPost(String url, Class clazz, Map<String, String> params, boolean isShowDialog) {
        initDialog(isShowDialog);
        GsonRequest request = new GsonRequest(Request.Method.POST, url, clazz, params, this, this);
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        return request;
    }

    protected GsonRequest getRequestForPut(String url, Class clazz, Map<String, String> params, boolean isShowDialog) {
        initDialog(isShowDialog);
        GsonRequest request = new GsonRequest(Request.Method.PUT, url, clazz, params, this, this);
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        return request;
    }

    protected GsonRequest getRequestForDelete(String url, Class clazz, boolean isShowDialog) {
        initDialog(isShowDialog);
        GsonRequest request = new GsonRequest(Request.Method.DELETE, url, clazz, this, this);
        request.setRetryPolicy(new DefaultRetryPolicy(30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        return request;
    }

    public void sendGETRequest(String url, Class clazz, boolean isShowDialog, Object tag) {
        VolleyHelper.getInstance().addRequest(getRequestForGet(url, clazz, isShowDialog), tag);
    }

    //    public void sendPUTRequest(String url,Class clazz,Map<String, String> params,boolean isShowDialog,Object tag){
//        VolleyHelper.getInstance().addRequest(getRequestForPut(url, clazz,params, isShowDialog), tag);
//    }
    public void sendPOSTRequest(String url, Class clazz, Map<String, String> params, boolean isShowDialog, Object tag) {
        VolleyHelper.getInstance().addRequest(getRequestForPost(url, clazz, params, isShowDialog), tag);
    }

    public void setOnResponseListener(OnResponseListener onResponseListener) {
        this.onResponseListener = onResponseListener;
    }

    public void sendPUTRequest(String url, Class clazz, Map<String, String> params, boolean isShowDialog, Object tag) {
        VolleyHelper.getInstance().addRequest(getRequestForPut(url, clazz, params, isShowDialog), tag);
    }

    public void sendDELETERequest(String url, Class clazz, boolean isShowDialog, Object tag) {
        VolleyHelper.getInstance().addRequest(getRequestForDelete(url, clazz, isShowDialog), tag);
    }

    private void initDialog(boolean isShowDialog) {
        if (isShowDialog) {
            if (dialog == null) {
                dialog = createLoadingDialog();
            }
            showDialog();
        }
    }

    private void showDialog() {
        try {
            if (dialog != null) {
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void cancelDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    private ProgressDialog progressDialog;

    private Dialog createLoadingDialog() {
//        LayoutInflater inflater = LayoutInflater.from(pContext);
//        View v = inflater.inflate(R.layout.loading_view, null);// 得到加载view
//
//        Dialog loadingDialog = new Dialog(pContext, R.style.loading_dialog);// 创建自定义样式dialog
//
//        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
//        loadingDialog.setCanceledOnTouchOutside(false);
//        loadingDialog.setContentView(v, new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
//        loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
//            @Override
//            public void onCancel(DialogInterface dialog) {
//            }
//        });
        progressDialog = new ProgressDialog(context.get());
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage("加载中...");
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    cancelDialog();
                    return true;
                }
                return false;
            }
        });

        return progressDialog;
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        cancelDialog();

        Toast.makeText(context.get(), "网络连接失败，请检查网络", Toast.LENGTH_SHORT).show();
        if (onResponseListener != null) {
            onResponseListener.onError(error);
        }
    }

    @Override
    public void onResponse(Object response) {
        cancelDialog();
        if (onResponseListener != null) {
            onResponseListener.onSuccess(response);
        }
    }

    public Dialog getDialog() {
        return dialog;
    }

    public void setDialog(Dialog dialog) {
        this.dialog = dialog;
    }
}
